import tkinter as tk
from tkinter import messagebox
import random
import json

# Load words from Excel file (assuming pandas is used)
import pandas as pd

df = pd.read_excel('A1words.xlsx')
english_words = df['German'].tolist()
chinese_words = df['English'].tolist()

# User profiles storage
profiles_file = 'user_profiles.json'

def load_profiles():
	try:
		with open(profiles_file, 'r') as f:
			return json.load(f)
	except FileNotFoundError:
		return {}

def save_profiles(profiles):
	with open(profiles_file, 'w') as f:
		json.dump(profiles, f)

# Initialize variables
current_stage = 1
attempts = 0
max_attempts = 1
flashcards = []
selected_language = 'Eng-Chn'

def load_flashcards(start_index):
	global flashcards
	if selected_language == 'Eng-Chn':
		flashcards = list(zip(english_words[start_index:start_index+20], chinese_words[start_index:start_index+20]))
	elif selected_language == 'Chn-Eng':
		flashcards = list(zip(chinese_words[start_index:start_index+20], english_words[start_index:start_index+20]))
	random.shuffle(flashcards)

def show_flashcard():
	global current_word, options, attempts, flashcards

	if not flashcards:
		if attempts < max_attempts:
			attempts += 1
			load_flashcards((current_stage - 1) * 20)
			show_flashcard()
		else:
			messagebox.showinfo("Game Over", "You've completed all stages!")
			root.destroy()
		return

	current_word = flashcards.pop()
	question_label.config(text=f"Translate this word: {current_word[0]}")

	correct_option = current_word[1]
	incorrect_options = [w[1] for w in flashcards[:3]] + [correct_option]
	random.shuffle(incorrect_options)

	for i, option in enumerate(incorrect_options):
		buttons[i].config(text=option, command=lambda o=option: check_answer(o))

def check_answer(selected_option):
	global current_stage, attempts
	if selected_option == current_word[1]:
		messagebox.showinfo("Correct", "Good job!")
		if not flashcards:
			current_stage += 1
			attempts = 0
			load_flashcards((current_stage - 1) * 20)
		show_flashcard()
	else:
		messagebox.showerror("Incorrect", f"Wrong answer. The correct answer is {current_word[1]}")
		show_flashcard()

def update_progress():
	total_steps = (current_stage - 1) * 20 + (20 - len(flashcards))
	progress_label.config(text=f"Total Steps: {total_steps}")

def set_language(lang):
	global selected_language
	selected_language = lang
	load_flashcards(0)
	show_flashcard()
	update_progress()

def save_profile():
	profiles = load_profiles()
	profiles[username] = {'stage': current_stage, 'attempts': attempts}
	save_profiles(profiles)
	messagebox.showinfo("Saved", "Your progress has been saved.")

def load_profile():
	global current_stage, attempts
	profiles = load_profiles()
	if username in profiles:
		current_stage = profiles[username]['stage']
		attempts = profiles[username]['attempts']
		load_flashcards((current_stage - 1) * 20)
		show_flashcard()
		update_progress()
		messagebox.showinfo("Loaded", "Your progress has been loaded.")
	else:
		messagebox.showwarning("Not Found", "No saved progress found for this user.")

# Set up the GUI
root = tk.Tk()
root.title("Flashcard App")
root.geometry("400x500")
root.configure(bg='#f0f8ff')

# Top bar with total progress and language selection
top_bar = tk.Frame(root, bg='#b0e0e6', pady=10)
top_bar.pack(fill='x')
progress_label = tk.Label(top_bar, text="Total Steps: 0", font=("Helvetica", 12), bg='#b0e0e6')
progress_label.pack(side='left', padx=10)
lang_var = tk.StringVar(value='Eng-Chn')
tk.Radiobutton(top_bar, text="English to Chinese", variable=lang_var, value='Eng-Chn', command=lambda: set_language('Eng-Chn')).pack(side='left')
tk.Radiobutton(top_bar, text="Chinese to English", variable=lang_var, value='Chn-Eng', command=lambda: set_language('Chn-Eng')).pack(side='left')
save_button = tk.Button(top_bar, text="Save Progress", command=save_profile)
save_button.pack(side='right', padx=10)
load_button = tk.Button(top_bar, text="Load Progress", command=load_profile)
load_button.pack(side='right', padx=10)

# Username input field
username_frame = tk.Frame(root, bg='#f0f8ff', pady=10)
username_frame.pack(fill='x')
tk.Label(username_frame, text="Username:", font=("Helvetica", 12), bg='#f0f8ff').pack(side='left', padx=10)
username_entry = tk.Entry(username_frame)
username_entry.pack(side='left', padx=10)
username = ''
def set_username():
	global username
	username = username_entry.get()
	if not username:
		messagebox.showwarning("Input Error", "Please enter a valid username.")
	else:
		load_profile()
set_username_button = tk.Button(username_frame, text="Set Username", command=set_username)
set_username_button.pack(side='left', padx=10)

# Flashcard display area
question_label = tk.Label(root, text="", font=("Helvetica", 16), bg='#f0f8ff')
question_label.pack(pady=20)
buttons = []
for i in range(4):
	button = tk.Button(root, text="", font=("Helvetica", 14), width=20)
	button.pack(pady=5)
	buttons.append(button)

# Initial setup
load_flashcards(0)
show_flashcard()
update_progress()

root.mainloop()